<template>
  <div class="register">
    <form action="JavaScript:;" class="register-from" method="POST">
      <input type="text" placeholder="请输入注册账号" v-model="registerInfo.username" maxlength="12">
      <input type="password" placeholder="请输入密码" v-model="registerInfo.password" maxlength="12">
      <input type="email" placeholder="请输入邮箱" v-model="registerInfo.email">
      <input type="text" placeholder="请输入验证码" class="verification" v-model="registerInfo.code">
      <button type="button" class="code" @click="sendCode" :disabled="sendCodeBtn.disabled">{{sendCodeBtn.text}}</button>
      <button class="btn" @click="register">注册</button>
    </form>
  </div>
</template>

<script>
import { mapActions, mapMutations } from 'vuex';
export default {
  name: 'Register',

  data() {
    return {
      sendCodeBtn: { // 发送验证码按钮
        disabled: false, // 是否禁用
        text: '发送验证码' // 按钮文本
      },
      registerInfo: { // 注册信息
        username: '', // 用户名
        password: '', // 密码
        email: '', // 邮箱
        code: '' // 验证码
      }
    };
  },

  methods: {
    //发送手机验证码
    sendCode(){
      this.sendCodeBtn.disabled = true
      this.sendCodeBtn.text = 60
      let timer = setInterval(() => {
        this.sendCodeBtn.text--
        if(this.sendCodeBtn.text == 0){
          this.sendCodeBtn.disabled = false
          this.sendCodeBtn.text = '发送验证码'
          clearInterval(timer)
        }
      }, 1000)
      if(this.registerInfo.email.trim()){
        this.$api.getEmailCode({
          email: this.registerInfo.email,
          type: 'register'
        }).then(res => {
          if(res == 1){
            this.showHint({title:'已发送',isFlag:true})
          }else{
            this.showHint({title:res,isFlag:true})
          }
        })
      }else{
        this.showHint({title:'邮箱不能为空!',isFlag:false})
        this.sendCodeBtn.text = 1
      }
    },
    // 注册账号
    register(){
      let {username,password,email,code} = this.registerInfo
      if(username.trim() && password.trim() && email.trim() && code.trim()){
        if(!/^[A-Za-z0-9]*$/.test(username)){
          this.showHint({title:'用户名只能是字母和数字组成!',isFlag:false})
        }else if(!/^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/.test(this.registerInfo.email)){
          this.showHint({title:'邮箱格式错误!',isFlag:false})
        }else if(username.length > 18 || username.length < 6 || password.length < 6 || password.length > 18){
          this.showHint({title:'用户名和密码6-18位!'})
        }else{
          this.$emit('changeRegister', this.registerInfo)
        }
      }else{
        this.showHint({title:'账号和密码不能为空!',isFlag:false})
      }
    },
    ...mapActions(['showHint']),
    ...mapMutations(['hideLoading'])
  },
};
</script>

<style scoped>
input{
  background-color: white;
}
input[disabled]{
  background-color: #ececec;
}
</style>